package com.mimc.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.upload.UploadFile;
import com.mimc.common.constant.AppConstants;
import com.mimc.common.enums.FileType;
import com.mimc.common.exception.ServiceException;
import com.mimc.common.utils.file.FileUtils;
import com.mimc.common.utils.file.ImageUtils;
import com.mimc.core.model.SysUploadFile;
import com.mimc.core.service.SysUploadFileService;
import com.mimc.framework.manager.vo.MinioConf;
import com.mimc.framework.utils.ShUtils;
import io.jboot.Jboot;
import io.jboot.aop.annotation.Bean;
import io.jboot.db.model.Columns;

import java.io.File;
import java.util.Date;

@Bean
public class ShUploadService {
    @Inject
    private ShSysConfigService shSysConfigService;
    @Inject
    private SysUploadFileService sysUploadFileService;
    @Inject
    private ShMinioService shMinioService;
    //上传图片
    public String uploadImage(UploadFile file, Integer groupId) throws Exception {
        String configValue=shSysConfigService.getConfigValueByKey("upload.settings");
        JSONObject jsonObj= JSON.parseObject(configValue);
        if(file.getFile().length() > AppConstants.MAX_IMAGE_SIZE){
            throw new ServiceException("文件大小不能超过5M");
        }
        // 图片格式校验
        if(!ImageUtils.isImage(file.getOriginalFileName())){
            throw new ServiceException("图片格式不合法");
        }
        String md5= FileUtils.md5OfFile(file.getFile());
        SysUploadFile uploadFileCk=sysUploadFileService.findFirstByColumns(Columns.create("md5",md5));
        if(uploadFileCk!=null){
            return uploadFileCk.getFileUrl()+"/"+uploadFileCk.getSaveName();
        }
        if(jsonObj.getString("default").equals("local")){
            //本地上传
            String uploadPath= Jboot.configValue("upload.path");
            String format = DateUtil.format(new Date(), "yyyyMMdd");
            String fileName = System.currentTimeMillis() + file.getOriginalFileName().substring(file.getOriginalFileName().lastIndexOf("."));
            String saveName = "image/"+format+"/"+fileName;
            File dest=new File(uploadPath+"/"+saveName);
            FileUtil.copy(file.getFile(),dest,true);
            file.getFile().deleteOnExit();
            SysUploadFile uploadFile=new SysUploadFile();
            uploadFile.setStorage("local");
            uploadFile.setFileName(file.getOriginalFileName());
            uploadFile.setSaveName(saveName);
            uploadFile.setMd5(md5);
            uploadFile.setGroupId(groupId);
            uploadFile.setFileSize(Integer.parseInt(file.getFile().length()+""));
            uploadFile.setFileType("image");
            uploadFile.setExtension(FileUtils.getFileExtendName(FileUtils.file2byte(file.getFile())));
            uploadFile.setIsUser(false);
            uploadFile.setFileUrl(ShUtils.getLocalConf().getDomain());
            uploadFile.setIsRecycle(false);
            uploadFile.setIsDelete(false);
            uploadFile.setCreateTime(new Date());
            uploadFile.setUpdateTime(new Date());
            sysUploadFileService.save(uploadFile);
            return ShUtils.getLocalConf().getDomain()+"/"+saveName;
        }else if(jsonObj.getString("default").equals("minio")){
            //minio上传
            MinioConf minioConf=ShUtils.getMinioConf();
            String fileName=shMinioService.upload("image",file);
            if(fileName!=null){
                //删除本地文件
                file.getFile().deleteOnExit();
                String url = generUrl(FileType.IMAGE,fileName);
                SysUploadFile uploadFile=new SysUploadFile();
                uploadFile.setStorage("minio");
                uploadFile.setFileName(file.getOriginalFileName());
                String saveName = minioConf.getBucket()+"/image/"+fileName;
                uploadFile.setSaveName(saveName);
                uploadFile.setMd5(md5);
                uploadFile.setFileSize(Integer.parseInt(file.getFile().length()+""));
                uploadFile.setFileType("image");
                uploadFile.setExtension(FileUtils.getFileExtendName(FileUtils.file2byte(file.getFile())));
                uploadFile.setIsUser(false);
                uploadFile.setFileUrl(minioConf.getDomain());
                uploadFile.setIsRecycle(false);
                uploadFile.setIsDelete(false);
                uploadFile.setGroupId(groupId);
                uploadFile.setCreateTime(new Date());
                uploadFile.setUpdateTime(new Date());
                sysUploadFileService.save(uploadFile);
                return url;
            }else{
                return null;
            }
        }
        return null;
    }
    public String generUrl(FileType fileTypeEnum, String fileName){
        MinioConf minioConf=ShUtils.getMinioConf();
        String url = minioConf.getDomain()+"/"+minioConf.getBucket();
        switch (fileTypeEnum){
            case FILE:
                url += "/file/";
                break;
            case IMAGE:
                url += "/image/";
                break;
            case VIDEO:
                url += "/video/";
                break;
        }
        url += fileName;
        return url;
    }
}
